import { getData } from '@vimi/utils-api'
import { cascaderParse } from '@vimi/utils-tool'

const state = {
  customerDept: [],
  customerDeptTree: [],
}

const getters = {
  customerDept: state => state.customerDept,
  customerDeptTree: state => state.customerDeptTree,
}

const actions = {
  getCustomerDept({ commit }, id) {
    return new Promise((resolve, reject) => {
      if (!id) {
        return resolve()
      }
      getData('credit', 'datum_customer_dept', { 'customer_related_id.eq': id })
        .then(res => {
          const data = res.data || []
          commit('customerDept', data)
          commit(
            'customerDeptTree',
            cascaderParse({
              data: data,
              key: 'datum_customer_dept_id',
              parentKey: 'parent_dept_id',
            })
          )
          resolve(data)
        })
        .catch(err => {
          reject(err)
        })
    })
  },
}

const mutations = {
  customerDept: (state, payload) => (state.customerDept = payload),
  customerDeptTree: (state, payload) => (state.customerDeptTree = payload),
}

export default {
  state,
  getters,
  actions,
  mutations,
}
